package com.ruoyi.my.controller.aliyunoss;

import com.aliyun.oss.*;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.my.domian.aliyunoss.OssUpload;
import com.ruoyi.my.service.aliyunoss.OssService;
import com.ruoyi.my.utils.aliyunoss.AccessToken;
import com.ruoyi.my.utils.aliyunoss.UploadFile;
import com.ruoyi.system.service.ISysDictDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/aliyunoss/oss")
public class OssController extends BaseController {

    @Autowired
    ISysDictDataService iSysDictDataService;

    @Autowired
    OssService ossService;

    /**
     * 获取课程列表
     */
    @PreAuthorize("@ss.hasPermi('aliyunoss:oss:list')")
    @GetMapping("/list")
    public TableDataInfo list(OssUpload ossUpload) {
        startPage();
        List<OssUpload> list = ossService.selectOssUploadList(ossUpload);
        return getDataTable(list);
    }


    @PreAuthorize("@ss.hasPermi('aliyunoss:oss:upload')")
    @PostMapping("/upload")
    public AjaxResult upload(MultipartFile file){
        String bucketName = iSysDictDataService.selectDictLabel("aliyun_oss","bucketName");
        String accessKeyId = iSysDictDataService.selectDictLabel("aliyun_oss","AccessKey_ID");
        String accessKeySecret = iSysDictDataService.selectDictLabel("aliyun_oss","AccessKey_Secret");
        String endpoint = iSysDictDataService.selectDictLabel("aliyun_oss","endpoint");
        String region = iSysDictDataService.selectDictLabel("aliyun_oss","region");
        String fileName = UploadFile.extractFilename(file);
        OSS ossClient = AccessToken.getOSSClient(accessKeyId, accessKeySecret, endpoint, region);
        String url = UploadFile.upload(file,endpoint,bucketName,fileName,ossClient);
        if (url != null){
            return AjaxResult.success(200,"上传成功！", url);
        }
        return AjaxResult.error();
    }

    /**
     * 删除课程
     */
    @PreAuthorize("@ss.hasPermi('aliyunoss:oss:delete')")
    @DeleteMapping("/{ossIds}")
    public AjaxResult remove(@PathVariable Long[] ossIds) {
        return toAjax(ossService.deleteOssByIds(ossIds));
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('aliyunoss:oss:update')")
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody OssUpload ossUpload) {
        return toAjax(ossService.updateOssById(ossUpload));
    }

    @PreAuthorize("@ss.hasPermi('aliyunoss:oss:add')")
    @PostMapping
    public AjaxResult addOss(@Validated @RequestBody OssUpload ossUpload) {
        return toAjax(ossService.addOss(ossUpload));
    }

}
